package com.lcx.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcx.db137.common.R;
import com.lcx.db137.entity.Menu;
import com.lcx.db137.entity.User;
import com.lcx.db137.service.MenuService;
import com.lcx.db137.service.UserService;
import com.lcx.db137.service.impl.MenuServiceImpl;
import com.lcx.db137.service.impl.UserServiceImpl;
import com.lcx.db137.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (user)表控制层
 *
 * @author xxxxx
 */
@RestController
@CrossOrigin(origins = "*")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    /**
     * 根据用户名和密码进行登录
     *
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        User user1 = userService.login(user);
        if (user1 == null) {//登录成功
            //生成token
            //
        }
        List<Menu> menus = menuService.selectMenuByUserId(user1.getId());
        map.put("user", user1);
        map.put("menus", menus);
        return map;
    }

    @PostMapping("/login1")
    public R login1(@RequestBody User user) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(user);
        User user1 = userService.getOne(queryWrapper);
        if (user1 != null) {//登录成功
            //生成token
            Map<String, Object> map = new HashMap<>();
            map.put("userid", user1.getId());
            String jwtToken = JwtUtils.createJwtToken(map);
            return new R().add("token", jwtToken);
        }
        return new R().setCode(500).setMessage("登录失败!");

//        List<Menu> menus = menuService.selectMenuByUserId(user1.getId());

    }

    //注册
    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        return userService.save(user);
    }
    //查询所有用户
    @RequestMapping("/getAllUser")
    public R getAllUser() {
        List<User> list = userService.list();
        return new R().add("list", list);
    }

    //新增用户
    @PostMapping("/addUser")
    public R addUser(@RequestBody User user) {
        boolean save = userService.save(user);
        return new R().add("b", save);
    }
    //修改用户
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user) {
        boolean update = userService.updateById(user);
        return new R().add("b", update);
    }


}
